<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');

$tmobile = cookieget('tmobile');
$tmobile = base64_decode($tmobile);
cookieset('tmobile', null, -1);


if ( $_POST ) {
	
	$u = array();
	$u['mobile'] = strval($_POST['mobile']);
	$u['username'] = strval($_POST['mobile']);
	$u['password'] = strval($_POST['password']);
	$u['enable'] = 'Y';
	
	$temp_mobile = strval($_POST['mobile']);
	cookieset('tmobile', base64_encode($temp_mobile), 30*86400);
	
	
	if ($_POST['password2']==$_POST['password'] && $_POST['password']) {
		//if ( option_yes('emailverify') || option_yes('mobilecode') ) { 
		//	$u['enable'] = 'N'; 
		//}
        if ( option_yes('emailverify')) { 
			$u['emailable'] = 'N'; 
		}
		
		$have = Table::Fetch('sms_verify', $u['mobile'], 'mobile');
		//$have = Table::Fetch('sms_verify', $_POST['sms_id'], 'id');
		if( !$have ){
			Session::Set('error', '非法尝试');
			redirect( WEB_ROOT . '/account/mobilesignup.php');
		}else{
			
			if ( (time() - $have['create_time']) > 60*30 ){
				Table::delete('sms_verify', $have['id']);
				Session::Set('error', '短信验证码已经过期了哦，请重新获取吧！');
				redirect( WEB_ROOT . '/account/mobilesignup.php');
			}
			
			if( strval($_POST['sms-verify-code']) != $have['mobilecode'] ){
				Session::Set('error', '短信验证码错误，请重新输入');
				redirect( WEB_ROOT . '/account/mobilesignup.php');
			}
			
			
			if( strval($_POST['sms-verify-code']) == $have['mobilecode'] ){
					
				//$u['id'] = $have['id'];
				Table::delete('sms_verify', $have['id']);
				cookieset('tmobile', null, -1);
				if ( $user_id = ZUser::CreateMobile($u) ) {
					ZCredit::Register($user_id);
					ZToolsbind::Create( $u['mobile'], $user_id, "" , true);
					if ( option_yes('emailverify') ) {
						mail_sign_id($user_id);
						Session::Set('unemail', $_POST['email']);
						redirect( WEB_ROOT . '/account/mobilesignuped.php');
					}else {
						ZLogin::Login($user_id);
						redirect(get_loginpage(WEB_ROOT . '/index.php'));
					}
				} else {
					$au = Table::Fetch('user', $_POST['email'], 'email');
					if ( $au ) {
						Session::Set('error', '注册失败，Email已被使用');
					} else {
						Session::Set('error', '注册失败，用户名已被使用');
					}
				}
			}
			
			
		}

		

	} else {
		Session::Set('error', '注册失败，密码设置有问题');
	}
}

$pagetitle = '注册';
include template('account_mobilesignup');
